package org.example.gui.model;

import org.example.dao.CategoryDAO;
import org.example.entity.Category;

import javax.swing.*;
import javax.swing.event.ListDataListener;
import java.util.List;

/**
 * CategoryPanel 的 ComboBox 的数据模型，实现了 ComboBoxModel<> 接口
 */

public class CategoryComboBoxModel implements ComboBoxModel<Category> {
    public List<Category> categoryList = CategoryDAO.listAllCategory();
    public Category category;

    public CategoryComboBoxModel() {
        if (!categoryList.isEmpty())
            category = categoryList.get(0);
    }

    @Override
    public int getSize() {
        return categoryList.size();
    }

    @Override
    public Category getElementAt(int index) {
        return categoryList.get(index);
    }

    @Override
    public void addListDataListener(ListDataListener l) {

    }

    @Override
    public void removeListDataListener(ListDataListener l) {

    }

    @Override
    //被选中就把选中的对象存到模型
    public void setSelectedItem(Object anItem) {
        category = (Category) anItem;
    }

    @Override
    //获取选中的时候从模型读出
    public Object getSelectedItem() {
        return category;
    }

}